import 'package:family_expense/features/account_user/models/join_account_group_request.dart';
import 'package:family_expense/features/account_user/services/join_account_group_request_service.dart';
import 'package:family_expense/features/account_user/widgets/user_shared.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class JoinAccountGroupRequestList extends StatefulWidget {
  const JoinAccountGroupRequestList({super.key});

  @override
  State<JoinAccountGroupRequestList> createState() =>
      _JoinAccountGroupRequestListState();
}

class _JoinAccountGroupRequestListState
    extends State<JoinAccountGroupRequestList> {
  final int _pageSize = GeneralConfig.listViewPageSize;

  final JoinAccountGroupRequestService _joinAccountGroupRequestService =
      JoinAccountGroupRequestService();

  // When action is taken we need to notify last page the change.
  bool _dataUpdated = false;

  // In order to refresh the list after item changes.
  late PagingListViewLoadController _loadController;

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: _onPopInvokedWithResult,
      child: Scaffold(
        appBar: AppBar(title: const Text('我的邀请')),
        body: _buildBody(),
      ),
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    return PagingListView(
      padding: const EdgeInsets.only(top: 10.0),
      pageSize: _pageSize,
      getLoadController: (loadController) => _loadController = loadController,
      retrieveData: (pageIndex) =>
          _joinAccountGroupRequestService.queryReceiving(_pageSize, pageIndex!),
      itemBuilder: (context, entry, index) => _buildListItem(entry),
    );
  }

  /// Builds list item to show request info.
  Widget _buildListItem(JoinAccountGroupRequest request) {
    return Card(
      margin: const EdgeInsets.all(10.0),
      color: Colors.grey[50],
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                SizedBox(width: 60.0, child: UserAvatorView(request.owner!)),
                const SizedBox(width: 6.0),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      request.owner!.fullName!,
                      style: Theme.of(context).textTheme.titleLarge,
                    ),
                    const SizedBox(height: 10.0),
                    Text(
                      request.owner!.username!.formatMobilePhoneNumber(),
                      style: Theme.of(context).textTheme.bodyMedium,
                    ),
                  ],
                ),
              ],
            ),
            const Divider(),
            Text(
              '用户 ${request.sender!.fullName} (${request.sender!.username!.formatMobilePhoneNumber()}) 于 ${request.lastUpdated.formatDate(DatePatterns.longDateTime)} 邀请您加入以上用户创建的账户组',
              style: Theme.of(context).textTheme.bodySmall,
            ),
            const Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                IconButton(
                  icon: const Icon(Icons.check, color: Colors.green),
                  tooltip: '接受',
                  onPressed: () => accept(request),
                ),
                IconButton(
                  icon: const Icon(Icons.clear, color: Colors.red),
                  tooltip: '拒绝',
                  onPressed: () => reject(request),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Future<void> accept(JoinAccountGroupRequest request) async {
    showConfirmDialog(
      context,
      '接受用户 ${request.sender!.fullName} (${request.sender!.username!.formatMobilePhoneNumber()}) 的邀请吗？',
      onConfirm: () async {
        // Show progress overlay.
        showInProgressOverlay(context);

        // Calls api.
        final success = await _joinAccountGroupRequestService.accept(
          request.id!,
        );

        // DO NOT use BuildContext across asynchronous gaps.
        // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
        if (mounted) {
          // Closes progress overlay.
          NavigatorHelper.pop(context);
        }

        if (success) {
          // Show taost.
          showToast('已成功接受，该消息已被清除，可至首页左上角切换账户组。');

          // Marks data has been changed.
          _dataUpdated = true;

          // Reloads data.
          _loadController.reset();
        }
      },
    );
  }

  Future<void> reject(JoinAccountGroupRequest request) async {
    showConfirmDialog(
      context,
      '拒绝用户 ${request.sender!.fullName} (${request.sender!.username!.formatMobilePhoneNumber()}) 的邀请吗？',
      onConfirm: () async {
        // Show progress overlay.
        showInProgressOverlay(context);

        // Calls api.
        final success = await _joinAccountGroupRequestService.reject(
          request.id!,
        );

        // DO NOT use BuildContext across asynchronous gaps.
        // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
        if (mounted) {
          // Closes progress overlay.
          NavigatorHelper.pop(context);
        }

        if (success) {
          // Show taost.
          showToast('已成功拒绝，该消息已被清除。');

          // Marks data has been changed.
          _dataUpdated = true;

          // Reloads data.
          _loadController.reset();
        }
      },
    );
  }

  void _onPopInvokedWithResult(bool didPop, dynamic result) {
    if (didPop) {
      return;
    }

    NavigatorHelper.pop(context, _dataUpdated);
  }
}
